package com.nianzhen.weight;

import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;

import java.lang.ref.WeakReference;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.TypedArray;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nianzhen.recruitment.R;
import com.nianzhen.utils.ScreenUtils;

public class MyAlertController {

	private final Context mContext;
	private final DialogInterface mDialogInterface;
	private final Window mWindow;

	private CharSequence mTitle;

	private CharSequence mMessage;

	private View mView;

	private int mViewSpacingLeft;

	private int mViewSpacingTop;

	private int mViewSpacingRight;

	private int mViewSpacingBottom;

	private boolean mViewSpacingSpecified = false;

	private boolean mbAutoBtnPosDismiss = true;
	private Button mButtonPositive;
    private ImageView mCloseBtn;

	private CharSequence mButtonPositiveText;

	private Message mButtonPositiveMessage;

	private TextView mTitleView;

	private TextView mMessageView;

	private Handler mHandler;

	View.OnClickListener mButtonHandler = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			
			boolean bDismiss = true;
			Message m = null;
			if (v == mButtonPositive && mButtonPositiveMessage != null) {
				m = Message.obtain(mButtonPositiveMessage);
				bDismiss = mbAutoBtnPosDismiss;
			}
			if (m != null) {
				m.sendToTarget();
			}

			// Post a message so we dismiss after the above handlers are
			// executed
			if (bDismiss || v == mCloseBtn)
			mHandler.obtainMessage(ButtonHandler.MSG_DISMISS_DIALOG,
					mDialogInterface).sendToTarget();
		}
	};

	private static final class ButtonHandler extends Handler {
		// Button clicks have Message.what as the BUTTON{1,2,3} constant
		private static final int MSG_DISMISS_DIALOG = 1;

		private WeakReference<DialogInterface> mDialog;

		public ButtonHandler(DialogInterface dialog) {
			mDialog = new WeakReference<DialogInterface>(dialog);
		}

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {

			case DialogInterface.BUTTON_POSITIVE:
			case DialogInterface.BUTTON_NEGATIVE:
			case DialogInterface.BUTTON_NEUTRAL:
				((DialogInterface.OnClickListener) msg.obj).onClick(
						mDialog.get(), msg.what);
				break;

			case MSG_DISMISS_DIALOG:
				((DialogInterface) msg.obj).dismiss();
			}
		}
	}

	public MyAlertController(Context context, DialogInterface di, Window window) {
		mContext = context;
		mDialogInterface = di;
		mWindow = window;
		mHandler = new ButtonHandler(di);
	}

	static boolean canTextInput(View v) {
		if (v.onCheckIsTextEditor()) {
			return true;
		}

		if (!(v instanceof ViewGroup)) {
			return false;
		}

		ViewGroup vg = (ViewGroup) v;
		int i = vg.getChildCount();
		while (i > 0) {
			i--;
			v = vg.getChildAt(i);
			if (canTextInput(v)) {
				return true;
			}
		}

		return false;
	}

	public void installContent() {
		/* We use a custom title so never request a window title */
//		mWindow.requestFeature(Window.FEATURE_NO_TITLE);

		if (mView == null || !canTextInput(mView)) {
			mWindow.setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
					WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
		}
		mWindow.setContentView(com.nianzhen.recruitment.R.layout.my_alert_dialog);
		DisplayMetrics metric = new DisplayMetrics();
		mWindow.getWindowManager().getDefaultDisplay().getMetrics(metric);
//		float density = metric.density;
		
//		if (DebugMode.mEnableLog)
//		Log.v("density", String.valueOf(density));
		
		int width = metric.widthPixels; // 屏幕宽度（像素）
//		int height = metric.heightPixels; // 屏幕高度（像素）
		android.view.WindowManager.LayoutParams para = mWindow.getAttributes();
//		if (width <= 240 || height <= 320) {
//			para.width = width;
//		} else {
//			para.width = (int) (300 * density);
//		}

        para.width = width;
        para.height = ((Activity)mContext).getWindow().getDecorView().getHeight() - ScreenUtils.getStatusHeight(mContext);
		para.gravity = Gravity.CENTER;
		mWindow.setAttributes(para);
		setupView();
	}

	public void setTitle(CharSequence title) {
		mTitle = title;
		if (mTitleView != null) {
			mTitleView.setText(title);
		}
	}

	public void setMessage(CharSequence message) {
		mMessage = message;
		if (mMessageView != null) {
			mMessageView.setText(message);
		}

	}

	/**
	 * Set the view to display in the dialog.
	 */
	public void setView(View view) {
		mView = view;
		mViewSpacingSpecified = false;
	}

	/**
	 * Set the view to display in the dialog along with the spacing around that
	 * view
	 */
	public void setView(View view, int viewSpacingLeft, int viewSpacingTop,
			int viewSpacingRight, int viewSpacingBottom) {
		mView = view;
		mViewSpacingSpecified = true;
		mViewSpacingLeft = viewSpacingLeft;
		mViewSpacingTop = viewSpacingTop;
		mViewSpacingRight = viewSpacingRight;
		mViewSpacingBottom = viewSpacingBottom;
	}

	/**
	 * Sets a click listener or a message to be sent when the button is clicked.
	 * You only need to pass one of {@code listener} or {@code msg}.
	 * 
	 * @param whichButton
	 *            Which button, can be one of
	 *            {@link DialogInterface#BUTTON_POSITIVE},
	 *            {@link DialogInterface#BUTTON_NEGATIVE}, or
	 *            {@link DialogInterface#BUTTON_NEUTRAL}
	 * @param text
	 *            The text to display in positive button.
	 * @param listener
	 *            The {@link DialogInterface.OnClickListener} to use.
	 * @param msg
	 *            The {@link Message} to be sent when clicked.
	 */
	public void setButton(int whichButton, CharSequence text,
			DialogInterface.OnClickListener listener, Message msg) {

		if (msg == null && listener != null) {
			msg = mHandler.obtainMessage(whichButton, listener);
		}

		switch (whichButton) {

		case DialogInterface.BUTTON_POSITIVE:
			mButtonPositiveText = text;
			mButtonPositiveMessage = msg;
			break;
		default:
			throw new IllegalArgumentException("Button does not exist");
		}
	}

	public Button getButton(int whichButton) {
		switch (whichButton) {
		case DialogInterface.BUTTON_POSITIVE:
			return mButtonPositive;
		default:
			return null;
		}
	}

	private void setupView() {
		LinearLayout contentPanel = (LinearLayout) mWindow
				.findViewById(R.id.contentPanel);
		setupContent(contentPanel);
		boolean hasButtons = setupButtons();

        RelativeLayout topPanel = (RelativeLayout) mWindow
				.findViewById(R.id.topPanel);
		TypedArray a = mContext.obtainStyledAttributes(null,
				com.android.internal.R.styleable.AlertDialog,
				com.android.internal.R.attr.alertDialogStyle, 0);
		setupTitle(topPanel);

		if (!hasButtons) {
            contentPanel.setBackgroundResource(R.drawable.white_round_shape);
		}

		FrameLayout customPanel = null;
		if (mView != null) {
			customPanel = (FrameLayout) mWindow
					.findViewById(R.id.customPanel);
            customPanel.addView(mView, new LayoutParams(MATCH_PARENT, MATCH_PARENT));
			if (mViewSpacingSpecified) {
                customPanel.setPadding(mViewSpacingLeft, mViewSpacingTop,
						mViewSpacingRight, mViewSpacingBottom);
			}
		} else {
			mWindow.findViewById(R.id.customPanel)
					.setVisibility(View.GONE);
		}

		a.recycle();
	}

	private int mLeftMessageIcon = -1;
	private int mTopMessageIcon = -1;

	public void setMessageLeftIcon(int resId){
		mLeftMessageIcon = resId;
	}

	public void setMessageTopIcon(int resId){
		mTopMessageIcon = resId;
	}

	private boolean setupTitle(RelativeLayout topPanel) {
		boolean hasTitle = true;

		mTitleView = (TextView) mWindow
				.findViewById(R.id.alertTitle);
		

		final boolean hasTextTitle = !TextUtils.isEmpty(mTitle);

		if (hasTextTitle) {
				/* Display the title if a title is supplied, else hide it */
			mTitleView.setText(mTitle);
		} else {
			//mWindow.findViewById(R.id.titleDividerTop).setVisibility(View.GONE);
			// Hide the title template
			mTitleView.setVisibility(View.GONE);
			topPanel.setVisibility(View.GONE);
			hasTitle = false;
		}
		return hasTitle;
	}

	private void setupContent(LinearLayout contentPanel) {

		// Special case for users that only want to display a String
		mMessageView = (TextView) mWindow
				.findViewById(R.id.message_tv);
		if (mMessageView == null) {
			return;
		}

		if (mMessage != null) {
			mMessageView.setText(mMessage);
		} else {
			mMessageView.setVisibility(View.GONE);
			contentPanel.findViewById(R.id.messageView).setVisibility(View.GONE);
		}
		ImageView topIcon = (ImageView) mWindow.findViewById(R.id.message_top_iv);
		if (mTopMessageIcon != -1 && topIcon != null){
			topIcon.setImageResource(mTopMessageIcon);
		}

		ImageView leftIcon = (ImageView) mWindow.findViewById(R.id.message_left_iv);
		if (mLeftMessageIcon != -1 && leftIcon != null){
			leftIcon.setImageResource(mLeftMessageIcon);
		}
	}

	private boolean setupButtons() {

        mCloseBtn = (ImageView)mWindow.findViewById(R.id.close_btn);
		mButtonPositive = (Button) mWindow
				.findViewById(R.id.button);

		mButtonPositive.setOnClickListener(mButtonHandler);
        mCloseBtn.setOnClickListener(mButtonHandler);
		if (TextUtils.isEmpty(mButtonPositiveText)) {
			mButtonPositive.setVisibility(View.GONE);
		} else {
			mButtonPositive.setText(mButtonPositiveText);
			mButtonPositive.setVisibility(View.VISIBLE);
		}

		return mButtonPositive.getVisibility() == View.VISIBLE;
	}

	public static class AlertParams {
		public final Context mContext;
		public final LayoutInflater mInflater;

		public int mMessageTopIconId = -1;
        public int mMessageLeftIconId = -1;
		public CharSequence mTitle;
		public CharSequence mMessage;
		public boolean mbAutoDismissPos = true;
		public CharSequence mPositiveButtonText;
		public DialogInterface.OnClickListener mPositiveButtonListener;
		public boolean mCancelable;
		public DialogInterface.OnCancelListener mOnCancelListener;
		public DialogInterface.OnKeyListener mOnKeyListener;
		public View mView;
		public int mViewSpacingLeft;
		public int mViewSpacingTop;
		public int mViewSpacingRight;
		public int mViewSpacingBottom;
		public boolean mViewSpacingSpecified = false;
		public boolean mForceInverseBackground;
		public boolean mRecycleOnMeasure = true;

		public AlertParams(Context context) {
			mContext = context;
			mCancelable = true;
			mInflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		public void apply(MyAlertController dialog) {

		    if (mTitle != null) {
			    dialog.setTitle(mTitle);
		    }

			if (mMessageLeftIconId != -1){
				dialog.setMessageLeftIcon(mMessageLeftIconId);
			}
			if (mMessageTopIconId != -1){
				dialog.setMessageTopIcon(mMessageTopIconId);
			}

			if (mMessage != null) {
				dialog.setMessage(mMessage);
			}
			if (mPositiveButtonText != null) {
				dialog.setButton(DialogInterface.BUTTON_POSITIVE,
						mPositiveButtonText, mPositiveButtonListener, null);
				
				dialog.mbAutoBtnPosDismiss = mbAutoDismissPos;
			}


			if (mView != null) {
				if (mViewSpacingSpecified) {
					dialog.setView(mView, mViewSpacingLeft, mViewSpacingTop,
							mViewSpacingRight, mViewSpacingBottom);
				} else {
					dialog.setView(mView);
				}
			}

		}
    }
}

